package com.fone.player.activity.search;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.yunzhisheng.basic.USCRecognizerDialog;
import cn.yunzhisheng.basic.USCRecognizerDialogListener;
import cn.yunzhisheng.common.USCError;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.search.adapter.SearchResultViewPagerAdapter;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.view.ColorBallProgressView;
import com.fone.player.view.HistorySearchPopWindow;
import com.fone.player.view.HistorySearchPopWindow.IDeleteListener;
import com.fone.player.view.PagerSlidingTab;

public class SearchResultActivity extends BaseActivity implements
		OnClickListener {

	public static SearchResultActivity searchResultActivity;
	private String TAG = "SearchResultActivity";
	private EditText et_search_result_content;
	private Button btn_search_result_back;
	public ViewPager mViewPager;
	private ImageView iv_search_result_voice;
	private ImageView iv_search_result_clear;
	private List<String> mHistoryWords;
	private TextView tv_search;
	private PagerSlidingTab tabs;
	private WebView mWebView;
	private String key_word;
	private String url;
	private TextView tv_loading;
	private View loading_view;
	private String SP = "search", FILE_NAME = "historyword";
	private SharedPreferences sp;
	private HistorySearchPopWindow popWindow;
	private int searchType;
	public int MEDIAPAGE = 0, ALLPAGE = 1;// 分别表示 影视剧页面和综合视频页面
	public int mCurrentPageID = MEDIAPAGE;// 当前页面
	private View loadingView;
	private ColorBallProgressView progressView;
	public static int mSearchType = -1;
	
	public Handler mHandler = null;
	public static final int SHOW_WAITING = 0;
	public static final int CANCLE_WAITING = 1;
	public static final int DO_SEARCH = 2;
	
	
	private long preClickTime; //记录上次点击返回键的事件,间隔两次返回键的时间 保证webView已经返回到首页
	private long preClicktime; 
	
	private SearchResultViewPagerAdapter mSearchResultViewPagerAdapter;
	
//	private ArrayList<String> urlList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		searchResultActivity = this;
		setContentView(R.layout.search_result_view);
		initHandler();
		initView();
		initData();
	}
	
	private void initHandler(){
		mHandler = new Handler(getMainLooper()){

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SHOW_WAITING:
					loadingView.setVisibility(View.VISIBLE);
					progressView.setVisibility(View.VISIBLE);
					break;
					
				case CANCLE_WAITING:
					loadingView.setVisibility(View.GONE);
					progressView.setVisibility(View.GONE);
					break;
					
				case DO_SEARCH:
					if(FoneUtil.isNetOkWithToast(mContext)){
						Object[] obj = (Object[]) msg.obj;
						mWebView.setVisibility(View.GONE);
						loadingView.setVisibility(View.VISIBLE);
						progressView.setVisibility(View.VISIBLE);
						mSearchResultViewPagerAdapter.doSearch((String)obj[0], (Integer)obj[1]);
					}else{
						mWebView.setVisibility(View.GONE);
						loadingView.setVisibility(View.GONE);
						progressView.setVisibility(View.GONE);
					}
					break;

				default:
					break;
				}
			}
		};
	}

	private void initView() {
		et_search_result_content = (EditText) findViewById(R.id.et_search_content);
		btn_search_result_back = (Button) findViewById(R.id.btn_search_back);
		iv_search_result_clear = (ImageView) findViewById(R.id.iv_search_clear);
		iv_search_result_voice = (ImageView) findViewById(R.id.iv_search_voice);
		
		//viewpager tabs
		tabs = (PagerSlidingTab) findViewById(R.id.search_result_tabs);
		tabs.setTabWidthPx(getResources().getDisplayMetrics().widthPixels / 2);
		tabs.setTypeface(null, 0);
		tabs.setTextSize(ScreenUtil.dp2px(15));
		tabs.setTextColorResource(R.color.tab_unselect_color);
		tabs.setTextSelectedColorResource(R.color.tab_select_color);
		
		tabs.setIndicatorColorResource(R.color.tab_select_color);// 选中标签页底线
		tabs.setIndicatorHeight(3);
		
		tabs.setUnderlineColorResource(R.color.tab_select_color);// 标签页底线
		tabs.setUnderlineHeight(1);
		tabs.setOnPageChangeListener(new SearchResultPagerChangeListenr());
		tv_search = (TextView) findViewById(R.id.tv_search);
		btn_search_result_back.setOnClickListener(this);
		iv_search_result_voice.setOnClickListener(this);
		iv_search_result_clear.setOnClickListener(this);
		tv_search.setOnClickListener(this);
		
		//ViewPager
		mViewPager = (ViewPager) findViewById(R.id.vp_search_result_result);
		int pageMargin = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 2, getResources()
						.getDisplayMetrics());
		mViewPager.setPageMargin(pageMargin);
		mSearchResultViewPagerAdapter = new SearchResultViewPagerAdapter();
		mViewPager.setAdapter(mSearchResultViewPagerAdapter);
		tabs.setViewPager(mViewPager);
		
		tabs.setChildTabText(0, mContext.getResources().getString(R.string.search_film));
		tabs.setChildTabText(1, mContext.getResources().getString(R.string.search_all));
		
		//loading
		loadingView = findViewById(R.id.rl_loading_view);
		loadingView.setVisibility(View.VISIBLE);
		loadingView.setOnClickListener(this);
		progressView = (ColorBallProgressView) findViewById(R.id.pb_search_result);
		progressView.setVisibility(View.VISIBLE);
		
		
		//searchTextView
		et_search_result_content.addTextChangedListener(new MyTextWatcher());
		et_search_result_content.setOnClickListener(this);
		et_search_result_content
				.setOnFocusChangeListener(new OnFocusChangeListener() {
					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (hasFocus) {
							showHistorySearchPopWindow();
						}
					}
				});

		
		// init webview
		mWebView = (WebView) findViewById(R.id.webview_search_result);
		loading_view = findViewById(R.id.search_result_loading);
		tv_loading = (TextView) findViewById(R.id.tv_search_result_loading);

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String keyWord = intent.getStringExtra(SearchActivity.KeyWord);
		searchType = intent.getIntExtra(SearchActivity.SearchType, 3);
		L.v(TAG, "onNewIntent","keyWord : " + keyWord +", searchType : " + searchType);
		et_search_result_content.setText(keyWord);
		et_search_result_content.clearFocus();
		if(!TextUtils.isEmpty(keyWord)){
			mViewPager.setCurrentItem(0);
			doServerSearch(keyWord, searchType);
		}
		
	}
	
	private class SearchResultPagerChangeListenr implements
			OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {}

		@Override
		public void onPageSelected(int arg0) {
			mCurrentPageID = arg0;
		}

	}

	private void initData() {
		
		// 读取搜索记录
		sp = mContext.getSharedPreferences(SP, MODE_PRIVATE);
		mHistoryWords = new ArrayList<String>();
		getHistoryWords();
		
		Intent intent = getIntent();
		String keyWord = intent.getStringExtra(SearchActivity.KeyWord);
		searchType = intent.getIntExtra(SearchActivity.SearchType, 3);
		et_search_result_content.setText(keyWord);
		et_search_result_content.clearFocus();
		doServerSearch(keyWord, searchType);
		
		popWindow = new HistorySearchPopWindow(mContext, mHistoryWords,
				et_search_result_content);

		popWindow.setDeleteListener(new IDeleteListener() {
			@Override
			public void deleteAll() {
				mHistoryWords.clear();
				Editor editor = sp.edit();
				editor.putString(FILE_NAME, "");
				editor.commit();
			}

			@Override
			public void delete(int index) {
				mHistoryWords.remove(index);
				saveHistorySearchWords("");
			}

			@Override
			public void selectItem(int position) {
				String HistoryWord = mHistoryWords.get(position);
				et_search_result_content.setText(HistoryWord);
				et_search_result_content.setSelection(et_search_result_content
						.getText().toString().length());
				doServerSearch(HistoryWord, SearchActivity.SEARCH_NORMAL);
			}
		});
	}

	private void doServerSearch(String keyWord, int type){
		if (TextUtils.isEmpty(keyWord)) {
			String no_search_word = mContext.getResources().getString(
					R.string.no_search_word);
			Toast.makeText(mContext, no_search_word, Toast.LENGTH_SHORT).show();
			return;
		}
		
		saveHistorySearchWords(keyWord);//保存搜做记录
		if (FoneUtil.isNetOkWithToast(mContext)) {
			if(mWebView != null && mWebView.getVisibility() == View.VISIBLE){
				
				loadingView.setVisibility(View.VISIBLE);
				progressView.setVisibility(View.VISIBLE);
						mWebView.stopLoading();
				if(mWebView.canGoBack()) {
					//会退到首页
					mWebView.goBackOrForward(-mWebView.copyBackForwardList().getCurrentIndex());
				}
			
				while(mWebView.canGoBack()){
					L.v(TAG, "doServerSearch"," waitting mWebView back to the first page !!! ");
				}
			}
			
			if(mHandler!=null){
				Message msg = mHandler.obtainMessage(DO_SEARCH);
				Object[] obj = new Object[]{keyWord,type};
				msg.obj = obj;
				mHandler.sendMessageAtFrontOfQueue(msg);
			}
		}
	}
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_search_content:
			showHistorySearchPopWindow();
			break;
		case R.id.btn_search_back:
			finish();
			break;
		case R.id.iv_search_voice:
			if (FoneUtil.isNetOkWithToast(mContext)) {
				doVoiceSearch();
			}
			break;

		case R.id.rl_web_search:
		case R.id.rl_web_search_all:
			if (FoneUtil.isNetOkWithToast(mContext)) {
				key_word = et_search_result_content.getText().toString();
				if (!TextUtils.isEmpty(key_word)) {
					doWebSearch();
				} else {
					FoneUtil.showToast(mContext, R.string.no_search_word);
				}
			}
			break;
		case R.id.iv_search_clear:
			et_search_result_content.setText("");
			break;
		case R.id.tv_search:
			if (FoneUtil.isNetOkWithToast(mContext) && isClickValid()) {
				key_word = et_search_result_content.getText().toString().trim();
				searchType = SearchActivity.SEARCH_NORMAL;
				doServerSearch(key_word, SearchActivity.SEARCH_NORMAL);
				closeKeyBoard(et_search_result_content);
			}
			break;

		default:
			break;
		}
	}

	// 网页搜索
	@SuppressLint("SetJavaScriptEnabled")
	public void doWebSearch() {
		loading_view.setVisibility(View.VISIBLE);
		if(mWebView == null){
			mWebView = (WebView) findViewById(R.id.webview_search_result);
		}
		mWebView.setVisibility(View.VISIBLE);
		key_word = et_search_result_content.getText().toString().trim();
		if (TextUtils.isEmpty(key_word)) {
			FoneUtil.showToast(mContext, R.string.no_search_word);
			return;
		}
		try {
			url = "http://m.v.360.cn/android/search/index.php?kw="
					+ URLEncoder.encode(key_word.trim(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			L.i(TAG, "web url 出错了！" + key_word);
		}
		if (ScreenUtil.getScreenWidthPix(mContext) <= 480) {
			mWebView.setInitialScale(50);
		} else {
			mWebView.setInitialScale(75);
		}
		mWebView.loadUrl(url);
//		WebView.enablePlatformNotifications();
		WebSettings setting = mWebView.getSettings();
		setting.setAllowFileAccess(true);
		setting.setJavaScriptEnabled(true);
		setting.setDefaultZoom(WebSettings.ZoomDensity.FAR);
		setting.setSupportZoom(true);
		setting.setBuiltInZoomControls(false);
//		setting.setPluginsEnabled(true);
		setting.setPluginState(PluginState.ON);

		// setting.setCacheMode(WebSettings.LOAD_NO_CACHE);

		WebViewClient mWebClient = new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				L.v(TAG, "shouldOverrideUrlLoading beg url:", url);
				if (!FoneUtil.isNetOkWithToast(mContext)) {
					L.v(TAG, "shouldOverrideUrlLoading", "no net");
				} else {
					if (url != null
							&& (url.startsWith("http://") || url
									.startsWith("https://"))) {
						view.stopLoading();
						view.invalidate();
						view.loadUrl(url);
					}
				}
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				mWebView.getSettings().setBlockNetworkImage(true);
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onLoadResource(WebView view, String url) {
				L.v(TAG, "onLoadResource url:", url);
				super.onLoadResource(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				L.v(TAG, "onPageFinished end url:", url);
				if (mWebView != null) {
					mWebView.getSettings().setBlockNetworkImage(false);
				}
				super.onPageFinished(view, url);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				L.v(TAG, "onReceivedError description:", description);
				L.v(TAG, "onReceivedError errorCode:", "" + errorCode);
				L.v(TAG, "onReceivedError end url:", failingUrl);

			}
		};

		mWebView.setWebViewClient(mWebClient);
		mWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				return true;
			}

			@Override
			public boolean onJsTimeout() {
				L.v(TAG, "onJsTimeout", "onJsTimeout");
				return super.onJsTimeout();
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress > 95) {
					loading_view.setVisibility(View.INVISIBLE);
				}
				tv_loading.setText(newProgress + "%");
			}

		});

		mWebView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_UP:
					if (!v.hasFocus()) {
						v.requestFocus();
					}
					break;
				}
				return false;
			}
		});
	}

	// 开启语音搜索
	@SuppressLint("HandlerLeak")
	private void doVoiceSearch() {
		et_search_result_content.setText("");
		// 用的是原100TV的key
		String key = "wn4lo73d7shfmj5s2eco3punzojc2rrq3yv6ttaq";
		USCRecognizerDialog recognizer = new USCRecognizerDialog(this, key);
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (FoneUtil.isNetOkWithToast(mContext)) {
					String key_word = (String) msg.obj;
					key_word = key_word.trim();
					if (key_word != null && key_word.length() > 1) {
						if(key_word.contains("。")){
							key_word = key_word.substring(0,key_word.indexOf("。"));
						}
						et_search_result_content.setText(key_word);
						et_search_result_content
								.setSelection(key_word.length());
					}
				}
			}
		};
		recognizer.setListener(new USCRecognizerDialogListener() {
			@Override
			public void onEnd(USCError arg0) {

			}

			StringBuffer sb = new StringBuffer();

			@Override
			public void onResult(String arg0, boolean arg1) {
				sb.append(arg0);
				if (arg1) {
					Message msg = new Message();
					msg.obj = sb.toString();
					handler.sendMessage(msg);
				}
			}
		});
		recognizer.show();
	}

	private class MyTextWatcher implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			if (s.length() > 0) {
				iv_search_result_voice.setVisibility(View.GONE);
				tv_search.setVisibility(View.VISIBLE);
				iv_search_result_clear.setVisibility(View.VISIBLE);
			} else {
				iv_search_result_voice.setVisibility(View.VISIBLE);
				tv_search.setVisibility(View.GONE);
				iv_search_result_clear.setVisibility(View.INVISIBLE);
			}
		}
	}

	// 保存历史搜索记录
	private void saveHistorySearchWords(String key_word) {
		if (!TextUtils.isEmpty(key_word)) {
			if (mHistoryWords.contains(key_word)) {
				mHistoryWords.remove(key_word);
			}
			mHistoryWords.add(0, key_word);
		}
		while (mHistoryWords.size() > 10) {
			mHistoryWords.remove(10);
		}
		String str = "";
		for (int i = mHistoryWords.size() - 1; i >= 0; i--) {
			String historyword = mHistoryWords.get(i);
			if (TextUtils.isEmpty(historyword)) {
				continue;
			}
			L.i(TAG, "save history word:" + mHistoryWords.get(i));
			str = str + ";;" + mHistoryWords.get(i);
		}
		L.i(TAG, "all history words :" + str);
		str = str.replaceFirst(";;", "");
		Editor editor = sp.edit();
		editor.putString(FILE_NAME, str);
		editor.commit();
	}

	// 展示历史搜索popwindow
	private void showHistorySearchPopWindow() {
		String words = sp.getString(FILE_NAME, null);
		L.i(TAG, "历史记录 words:" + words);
		if (TextUtils.isEmpty(words)) {
			return;
		}
		String[] historyWords = words.split(";;");
		mHistoryWords.clear();
		if (historyWords != null) {
			for (int i = historyWords.length; i > 0; i--) {
				mHistoryWords.add(historyWords[i - 1]);
			}
			popWindow.showPop();
		}
		MyDeleteListener deleteListener = new MyDeleteListener();
		popWindow.setDeleteListener(deleteListener);
	}

	/**
	 * 获取搜索历史
	 */
	private void getHistoryWords(){
		String words = sp.getString(FILE_NAME, null);
		L.i(TAG, "历史记录 words:" + words);
		if (TextUtils.isEmpty(words)) {
			return;
		}
		String[] historyWords = words.split(";;");
		mHistoryWords.clear();
		if (historyWords != null) {
			for (int i = historyWords.length; i > 0; i--) {
				mHistoryWords.add(historyWords[i - 1]);
			}
		}
	}
	
	private class MyDeleteListener implements IDeleteListener {
		@Override
		public void deleteAll() {
			mHistoryWords.clear();
			Editor editor = sp.edit();
			editor.putString(FILE_NAME, "");
			editor.commit();
		}

		@Override
		public void delete(int index) {
			mHistoryWords.remove(index);
			saveHistorySearchWords("");
		}

		@Override
		public void selectItem(int position) {
			String HistoryWord = mHistoryWords.get(position);
			et_search_result_content.setText(HistoryWord);
			et_search_result_content.setSelection(et_search_result_content
					.getText().toString().length());
			doServerSearch(HistoryWord, SearchActivity.SEARCH_NORMAL);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& popWindow.searchPopWindowisShowing()) {
			popWindow.dismissSearchPopWindow();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK
				&& mWebView.getVisibility() == View.VISIBLE) {
			
			if(System.currentTimeMillis()-preClickTime<300){
				L.v(TAG, "onKeyDown"," too fast to goback the webview !!!");
				return true;
			}
			preClickTime = System.currentTimeMillis();
			
			if (mWebView != null) {
				mWebView.stopLoading();
				if (mWebView.canGoBack()) {
					try {
						L.v(TAG, "onKeyDown", "mWebView.onResume()");
						mWebView.getClass().getMethod("onResume").invoke(mWebView,(Object[])null);
					} catch (Exception e) {
						L.e(TAG, "onKeyDown", e.getMessage());
					}
					//回退到首页
					mWebView.goBackOrForward(-mWebView.copyBackForwardList().getCurrentIndex());
					
				} else {
					mWebView.clearView();
					mWebView.setVisibility(View.GONE);
					mViewPager.setVisibility(View.VISIBLE);
				}
			}
			return true;

		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	
	@Override
	protected void onResume() {
		if(mWebView!=null && mWebView.getVisibility() == View.VISIBLE){
			try {
				L.v(TAG, "onResume", "mWebView.onResume()");
				mWebView.getClass().getMethod("onResume").invoke(mWebView,(Object[])null);
			} catch (Exception e) {
				L.e(TAG, "onResume", e.getMessage());
			}
			
		}
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		if(mWebView!=null && mWebView.getVisibility() == View.VISIBLE){
			try {
				L.v(TAG, "onPause", "mWebView.onPause()");
				mWebView.getClass().getMethod("onPause").invoke(mWebView,(Object[])null);
			} catch (Exception e) {
				L.e(TAG, "onPause", e.getMessage());
			}
		}
		super.onPause();
	}
	
	/**
	 * 关闭软键盘
	 * 
	 * @param v
	 */
	private void closeKeyBoard(View v) {
		InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		manager.hideSoftInputFromWindow(v.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	/**
	 * 点击是否有效
	 * 
	 * @return
	 */
	private boolean isClickValid() {
		long currentTime = System.currentTimeMillis();
		if (currentTime - preClicktime < 1000) {
			L.v(TAG, " isClickValid ", " false ");
			return false;
		} else {
			preClicktime = currentTime;
			L.v(TAG, " isClickValid ", " true ");
			return true;
		}
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		searchResultActivity = null;
		if(mWebView!=null){
			mWebView.stopLoading();
			mWebView.clearCache(true);
			mWebView.clearView();
			mWebView.destroy();
			mWebView = null;
		}
		if(mViewPager!=null){
			mViewPager.removeAllViews();
			mViewPager.removeAllViewsInLayout();
			mViewPager = null;
		}
		if(mSearchResultViewPagerAdapter != null){
			mSearchResultViewPagerAdapter.removeData();
			mSearchResultViewPagerAdapter = null;
		}
		System.gc();
	}
}
